<script setup lang="ts">
import { ref } from 'vue'
import { Attach20Regular } from '@vicons/fluent'
import { Icon } from '@vicons/utils'
import { storeToRefs } from 'pinia'
import { useModelStore } from '@/stores/model'
import { message } from 'ant-design-vue'
import { useGlobalStore } from '@/stores/global'

// 模型存储
const modelStore = useModelStore()
const { readActiveModelInfo } = storeToRefs(modelStore)

// 全局存储
const globalStore = useGlobalStore()
const { bindAttachList } = storeToRefs(globalStore)

// 定义事件
const emits = defineEmits(['change'])

// 组件
const fileRef = ref()

// 选择文件
const onChooseFile = (e: any) => {
  const file = e.target.files[0] ?? null
  if (file) {
    if (bindAttachList.value.some((f) => f.name === file.name && f.size === file.size)) {
      message.warn(`"${file.name}"已添加，本次忽略`)
      return
    }
    if (!file.type.startsWith('image/')) {
      message.error('请选择图片文件')
      return
    }
    if (file.size > 10 * 1024 * 1024) {
      message.error('单个文件大小不能超过 10MB')
      return
    }
    if (bindAttachList.value.length > 10) {
      message.error('最多只能上传 10 个附件')
      return
    }
    emits('change', file)
    fileRef.value.value = ''
  }
}
</script>

<template>
  <a-tooltip placement="top">
    <template #title>
      <template v-if="!readActiveModelInfo">请先选择一个模型</template>
      <template v-else>
        <div>上传附件</div>
        <div class="limit">最多 10 个, 每个 10MB 以内, 仅支持图片</div>
      </template>
    </template>
    <n-button
      type="default"
      secondary
      :disabled="!readActiveModelInfo"
      @click="() => fileRef.click()"
    >
      <template #icon>
        <Icon><Attach20Regular /></Icon>
      </template>
    </n-button>
  </a-tooltip>
  <input type="file" ref="fileRef" @change="onChooseFile" style="display: none" accept="image/*" />
</template>

<style lang="scss" scoped>
.limit {
  font-size: 13px;
  margin-top: 5px;
  color: #bbb;
}
</style>
